package com.mysoft.main.main.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.mysoft.common.entity.Order;
import com.mysoft.main.main.web.AlipayConfig;
import com.mysoft.main.main.web.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @Author: JohnCoding
 * @Description: 马云支付
 * @date: 2019/12/28 11:25
 */
@RestController
@RequestMapping("/ali")
public class AliPayController {

    private static AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

    @PostMapping("aliRefund")
    @ApiOperation(value = "测试退款接口")
    public Result refund(HttpServletResponse response){
        Order order = new Order();
        order.setCode("123456");
        order.setName("测试订单");
        order.setMoney(66);
//        AlipayTradePageRefundRequest refundRequest = new AlipayTradePageRefundRequest();
        AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();
        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("out_trade_no",order.getCode());
        jsonObject.put("refund_amount",order.getMoney());
        jsonObject.put("trade_no","2019123022001438641000049725");
//        jsonObject.put("subject",order.getName());
//        jsonObject.put("product_code","FAST_INSTANT_TRADE_PAY");
        refundRequest.setBizContent(jsonObject.toJSONString());
        refundRequest.setNotifyUrl(AlipayConfig.notify_url);
        refundRequest.setReturnUrl(AlipayConfig.return_url);
        String result = null;
        PrintWriter writer = null;
        try {
            result = alipayClient.execute(refundRequest).getBody();
            writer = response.getWriter();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.print(result);
        return null;
    }

    @GetMapping("query")
    @ApiOperation(value = "程序订单接口")
    public Result query(HttpServletResponse response){
        Order order = new Order();
        order.setCode("123456");
        order.setName("测试订单");
        order.setMoney(50);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no",order.getCode());
//        jsonObject.put("refund_amount",order.getMoney());
//        jsonObject.put("subject",order.getName());
//        jsonObject.put("product_code","FAST_INSTANT_TRADE_PAY");
        request.setBizContent(jsonObject.toJSONString());
        request.setNotifyUrl(AlipayConfig.notify_url);
        request.setReturnUrl(AlipayConfig.return_url);
        String result = null;
        PrintWriter writer = null;
        try {
            result = alipayClient.execute(request).getBody();
            writer = response.getWriter();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.print(result);
        return null;
    }

    @GetMapping("aliPaySum")
    @ApiOperation(value = "测试支付接口")
    public Result aliPay(HttpServletResponse response) {
        System.out.println("aliPaySum");
        // 根据前端传过来的Order信息查询出Order
        Order order = new Order();
        order.setCode("123456");
        order.setName("测试订单");
        order.setMoney(66);
        // 获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no",order.getCode());
        jsonObject.put("total_amount",order.getMoney());
        jsonObject.put("subject",order.getName());
        jsonObject.put("product_code","FAST_INSTANT_TRADE_PAY");
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizContent(jsonObject.toJSONString());
        String result = null;
        String body = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.println(result);
        return null;
    }


    @PostMapping("notifyUrl")
    public Result notifyUrl(HttpServletRequest request){
        System.out.println("notifyUrl");
        //商品订单号
        try {
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "GBK");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "GBK");
            // 交易说明
            String cus = new String(request.getParameter("body").getBytes("ISO-8859-1"), "GBK");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "GBK");
            if (trade_status.equals("TRADE_SUCCESS")) {//支付成功商家操作
                //根据你的操作自行编写
                // 获取商户订单号
                String orderCode = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");
                //根据订单号修改订单状态为已付款  2
//                orderService.updateOrderStatus(orderCode,2);
                //return 重定向到我的订单界面或者其他页面
//                return "redirect:/order/showOrderView";
                return new Result().ok("支付成功 orderCode 为： "+ orderCode);
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("returnUrl")
    public Result returnUrl(HttpServletRequest request){
        System.out.println("returnUrl");
        //支付成功后的因袭可以通过 request.getParameterMap()获取到
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key:parameterMap.keySet()
        ) {
//            System.out.println(key);
//            System.out.println(parameterMap.get(key));
        }
        // 获取商户订单号
        try {
            String orderCode = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");
            return new Result().ok("支付成功 orderCode 为： "+ orderCode);
        } catch (UnsupportedEncodingException e) {
        }
        //根据订单号修改订单状态为已付款
//        orderService.updateOrderStatus(orderCode,Constants.ORDER_PAY_OK_TYPE);
        //return 重定向到我的订单界面或者其他页面
        return null;
    }


}
